#include "widgetmodbus.h"
#include "ui_widgetmodbus.h"

#include <QMessageBox>

WidgetModbus::WidgetModbus(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::WidgetModbus)
{
    ui->setupUi(this);



    ui->cbBaudrate->setEditable(true);

    //QRegExp regx("[1-9][0-9]+$");

    QRegExp regx("^([1-9]{1}|[1-9]{1}[0-9]{1}|1[0-9]{1}[0-9]{1}|2[0-4][0-7])$");

    QValidator *validator = new QRegExpValidator(regx, ui->etModbusAddress );
    ui->etModbusAddress->setValidator(validator);

	QIntValidator *validator1 = new QIntValidator(1, 9999, this);
	ui->etPeriod->setValidator(validator1);

    timerModbusQuery = new QTimer(this);
    connect(timerModbusQuery, SIGNAL(timeout()), this, SLOT(slotModbusQuery()));


}

WidgetModbus::~WidgetModbus()
{
    delete ui;
}

void WidgetModbus::SetUartRecerver(serialportio *tReceiver,QString productModal)
{
    this->sensorRecver_ = tReceiver;
    this->mProductModal = productModal;

	if (this->mProductModal == "TF03")
	{

	}

}

bool WidgetModbus::CheckComState()
{
    if(sensorRecver_==nullptr)
        return false;

    if(!sensorRecver_->isOpen())
    {
        QMessageBox::warning(NULL, "Error", tr(u8"未连接Com口"));
        return false;
    }

    return true;
}

void WidgetModbus::on_btnModbusContract_clicked()
{

        if(!CheckComState()) return;
        
   /*     if(ui->cbModbusContract->currentIndex()==0){
            if(sensorRecver_->send_cmd_id_modbus_enable())
            {
              QMessageBox::information(NULL, tr(u8"提示"), tr(u8"Modbus启用成功！"));
            }else
            {
              QMessageBox::critical(NULL, tr(u8"提示"), tr(u8"Modbus启用失败！"));
            }
        }else*/
        
        //关闭modbus协议就是转换到RS485
		qDebug() << "关闭Modbus";
        uint modbusAddress = ui->etModbusAddress->text().toUShort();
        if(sensorRecver_->send_cmd_id_mb_modbus_disable(modbusAddress))
        {
            QMessageBox::information(NULL, tr(u8"提示"), tr(u8"Modbus关闭成功！"));
			qDebug() << "关闭Modbus成功";
        }else
        {
            QMessageBox::critical(NULL, tr(u8"提示"), tr(u8"Modbus关闭失败！"));
			qDebug() << "关闭Modbus失败";
        }
        


}

void WidgetModbus::on_btnModbusAddress_clicked()
{
       if(!CheckComState()) return;
       uint modbusAddress = ui->etModbusAddress->text().toUShort();
       uint curModbusAddress = ui->etCurModbusAddress->text().toUInt();

	   qDebug() << "设置Modbus地址为:"<< modbusAddress<<" 原地址："<< curModbusAddress;

       if(sensorRecver_->send_cmd_id_mb_dev_addr_config(curModbusAddress,modbusAddress))
       {
         QMessageBox::information(NULL, tr(u8"提示"), tr(u8"modbus地址设置成功！"));
		 qDebug() << "Modbus地址设置成功";
       }
	   else
       {
        QMessageBox::critical(NULL, tr(u8"提示"), tr(u8"modbus地址设置失败！"));
		qDebug() << "Modbus地址设置失败";
       }
}

void WidgetModbus::on_btnBaudrate_clicked()
{
     if(!CheckComState()) return;

     uint Baudrate = ui->cbBaudrate->currentText().toUInt();

      uint curModbusAddress = ui->etCurModbusAddress->text().toUInt();

	  qDebug() << "设置波特率为:" << Baudrate;

     if(sensorRecver_->send_cmd_id_mb_baudrate_config(curModbusAddress, Baudrate))
     {
       QMessageBox::information(NULL, tr(u8"提示"), tr(u8"modbus波特率设置成功！"));
	   qDebug() << "设置波特率成功";
     }else
     {
       QMessageBox::critical(NULL, tr(u8"提示"), tr(u8"modbus波特率设置失败！"));
	   qDebug() << "设置波特率失败";
     }
}



void WidgetModbus::on_btnCurrentDistance_clicked()
{
       if(!CheckComState()) return;
       unsigned short dist;
	   qDebug() << "获取当前距离";
       uint curModbusAddress = ui->etCurModbusAddress->text().toUInt();
       if(sensorRecver_->send_cmd_id_mb_get_dist(curModbusAddress, dist))
       {
           ui->lbCurDistance->setText(tr(u8"当前距离:")+QString::number(dist));
		   qDebug() << "获取当前距离成功：距离为"<< dist;
       }
       else
       {
           QMessageBox::critical(NULL, tr(u8"提示"), tr(u8"距离获取失败！"));
		   qDebug() << "获取当前距离失败";
       }
}
/**
 * @brief WidgetModbus::on_btnCurSignal_clicked
 * 信号强度无协议！！！
 */
void WidgetModbus::on_btnCurSignal_clicked()
{

     if(!CheckComState()) return;
     unsigned short signal;
     uint curModbusAddress = ui->etCurModbusAddress->text().toUInt();
	 qDebug() << "获取当前信号强度";
     if(sensorRecver_->send_cmd_id_modbus_getsignal(curModbusAddress,signal))
     {
          ui->lbCurSignal->setText(tr(u8"信号强度:")+QString::number(signal));
		  qDebug() << "获取当前信号强度成功：强度为" << signal;
     }else{
           QMessageBox::critical(NULL, tr(u8"提示"), tr(u8"信号强度获取失败！"));
		   qDebug() << "获取当前信号强度失败";
     }

}

void WidgetModbus::on_btnSaveConfig_clicked()
{
       if(!CheckComState()) return;
        uint curModbusAddress = ui->etCurModbusAddress->text().toUInt();

		qDebug() << "保存当前配置";
       if(sensorRecver_->send_cmd_id_mb_save_config(curModbusAddress))
       {
           ui->lbSaveConfigResult->setText(tr(u8"配置保存成功"));
		   qDebug() << "保存当前配置成功";
       }else{
            ui->lbSaveConfigResult->setText(tr(u8"配置保存失败"));
		   qDebug() << "保存当前配置失败";
       }
}

void WidgetModbus::on_btnFrameFreq_clicked()
{
    if(!CheckComState()) return;
    ushort fps = ui->cbFrameFreq->currentText().toUShort();
    uint curModbusAddress = ui->etCurModbusAddress->text().toUInt();
	qDebug() << "设置频率为："<<fps;

    if(sensorRecver_->send_cmd_id_modbus_set_fps(curModbusAddress, fps))
    {
      QMessageBox::information(NULL, tr(u8"提示"), tr(u8"modbus帧率设置成功！"));

	  qDebug() << "设置频率成功";

    }else
    {
     QMessageBox::critical(NULL, tr(u8"提示"), tr(u8"modbus帧率设置失败！"));

	 qDebug() << "设置频率失败";
    }
}

bool WidgetModbus::CheckComStateNoMessage()
{
    if(sensorRecver_==nullptr)
        return false;

    if(!sensorRecver_->isOpen())
    {
        return false;
    }

    return true;
}


/**开始轮询获取距离
 * @brief WidgetModbus::on_btnStart_clicked
 */

void WidgetModbus::on_btnStart_clicked()
{
		try
		{

			if(!timerModbusQuery->isActive())
			{
				qDebug() << "开始轮询距离";

				int period = ui->etPeriod->text().toInt();
				if (period == 0)
				{
					QMessageBox::warning(NULL, tr(u8"提示"), tr("轮询周期不可以设置为0"));
					return;
				}

				sensorRecver_->iicFreq_ = 1000/ period;

				
				timerModbusQuery->setInterval(period);
				timerModbusQuery->start();

				ui->btnStart->setEnabled(false);
				ui->btnStop->setEnabled(true);
			}


		}
		catch (std::exception& ex)
		{
			qErrnoWarning(1001, ex.what());
			QMessageBox::warning(NULL, tr(u8"提示"), ex.what());
		}
		catch (...) {
			QMessageBox::warning(NULL, tr(u8"提示"), "exception");
		}

}


/**停止轮询获取距离
 * @brief WidgetModbus::on_btnStop_clicked
 */

void WidgetModbus::on_btnStop_clicked()
{
    if(timerModbusQuery->isActive())
    {
		qDebug() << "停止轮询距离";

        timerModbusQuery->stop();
        ui->btnStart->setEnabled(true);
        ui->btnStop->setEnabled(false);
    }
}

/**

*/
void WidgetModbus::slotModbusQuery()
{

    if(!CheckComStateNoMessage())
    {
       qDebug("Serial port is not opened");
       return;
    }

    uint curModbusAddress = ui->etCurModbusAddress->text().toUInt();
    if(sensorRecver_->send_mb_distandsignal(curModbusAddress))
    {
       qDebug("modbus data sampling signal sent successful");

    }else{

       qDebug("modbus data sampling signal sent fail");
    }

}

void WidgetModbus::on_btnMbContractSave_clicked()
{
	qDebug() << "保存配置";

    if(sensorRecver_->send_cmd_id_save_settings())
    {
        ui->lbConfigResult->setText(tr(u8"配置保存成功！"));
		qDebug() << "保存配置成功";
    }else
    {
       ui->lbConfigResult->setText(tr(u8"配置保存失败！"));
	    qDebug() << "保存配置失败";
    }



}
